package com.atguigu.ssyx.acl.utils;

import com.atguigu.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * @author suchengchen
 * @date 2023/9/5
 * @description
 */
public class PermissionHelper {

    public static List<Permission> buildPermission(List<Permission> allList) {

        List<Permission> trees = new ArrayList<>();

        allList.forEach(permission -> {
            if (permission.getPid() == 0) {
                permission.setLevel(1);
                trees.add(findChildren(permission, allList));
            }
        });

        return trees;
    }

    private static Permission findChildren(Permission permission, List<Permission> allList) {

        permission.setChildren(new ArrayList<Permission>());

        allList.forEach(item -> {
            if (permission.getId().equals(item.getPid())) {
                int level = permission.getLevel() + 1;
                item.setLevel(level);
                if (permission.getChildren() == null) {
                    permission.setChildren(new ArrayList<>());
                }
                permission.getChildren().add(findChildren(item, allList));
            }
        });
        return permission;
    }

}
